﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using umbraco.cms.businesslogic.web;
using umbraco.cms.businesslogic.property;

namespace Juzzbott.Ulib
{
	public class UmbracoDocument
	{

		#region Get Property Value

		/// <summary>
		/// Gets the property value based on the property name.
		/// </summary>
		/// <param name="document">The document to get the property value from.</param>
		/// <param name="propertyName">The name (alias) of the property to get the value for.</param>
		/// <returns>The property value, or "" (empty string) if the property does not exist or is empty.</returns>
		public static string GetPropertyValue(Document document, string propertyAlias)
		{
			return GetPropertyValue(document, propertyAlias, "");
		}

		/// <summary>
		/// Gets the property value based on the property name.
		/// </summary>
		/// <param name="document">The document to get the property value from.</param>
		/// <param name="propertyName">The name (alias) of the property to get the value for.</param>
		/// <param name="defaultValue">The value to use if the property does not exist or is empty.</param>
		/// <returns>The property value, or defaultValue if the property does not exist or is empty.</returns>
		public static string GetPropertyValue(Document document, string propertyAlias, string defaultValue)
		{
			return GetPropertyValue<string>(document, propertyAlias, defaultValue);
		}

		/// <summary>
		/// Gets the property value based on the property name.
		/// </summary>
		/// <typeparam name="T">The type of object to return the value as.</typeparam>
		/// <param name="document">The document to get the property value from.</param>
		/// <param name="propertyAlias">The name (alias) of the property to get the value for.</param>
		/// <param name="defaultValue">The value to use if the property does not exist or is empty.</param>
		/// <returns>The property value, or defaultValue if the property does not exist or is empty.</returns>
		public static T GetPropertyValue<T>(Document document, string propertyAlias, T defaultValue)
		{
			
			// Get the property
			Property theProp = (Property)document.getProperty(propertyAlias);

			// if the property does not exist, the value is empty or null, then return default value
			if (theProp == null || theProp.Value == null)
			{
				return defaultValue;
			}
			else
			{

				// Try to convert the value to the given type
				try
				{

					// return the value as the specified type
					T propertyValue = (T)Convert.ChangeType(theProp.Value, typeof(T));

					// return the value
					return propertyValue;

				}
				catch (Exception)
				{
					// Error converting value, so return default value
					return defaultValue;
				}
			}

		}

		#endregion

	}
}
